package com.seashell.appstartupjob.worker.work;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import com.seashell.appstartupjob.enums.CopyType;
import org.apache.commons.lang3.StringUtils;

/**
 * com.seashell.appstartupjob.worker.work.TransFileWork
 * Jar包内文件移动到目标地址工具类
 *
 * @author Allen
 * @version v1.0
 * @date 2017/7/17
 */
public class TransFileWork {

	/**
	 * 移动Jar包内文件到指定地址
	 * @param jarFile jar包文件
	 * @param entry 要移动文件entry
	 * @param resourcePathCut 原始包内路径切除部分
	 * @param destinationRootPath 目标地址根路径
	 * @param copyType copy类型 覆盖或略过
	 * @throws IOException
	 */
	public static void trans(JarFile jarFile, JarEntry entry, String resourcePathCut,
							 String destinationRootPath,
							 CopyType copyType)
			throws IOException {
		// 文件目标地址
		String oriPath = entry.getName();
		if(StringUtils.isNotEmpty(resourcePathCut)){
			if(oriPath.indexOf(resourcePathCut)==0){
				oriPath = oriPath.substring(resourcePathCut.length(),oriPath.length());
			}
		}
		String fileName = destinationRootPath + oriPath;

		File file = new File(fileName);
		// 判断拷贝类型
		boolean doCopy = false;
		if (file.exists()) {
			if (CopyType.OVERRIDE == copyType) {
				doCopy = true;
				file.delete();
			}
		} else {
			doCopy = true;
		}
		// 执行copy
		if (doCopy) {
			try (InputStream in = jarFile.getInputStream(entry); FileOutputStream out = new FileOutputStream(file)) {
				byte[] temp = new byte[1024];
				while (in.read(temp) != -1) {
					out.write(temp);
				}
			}
		}
	}
}
